package com.kaede.hayate.modules.sys.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaede.hayate.modules.sys.entity.User;
import com.kaede.hayate.modules.sys.entity.UserRole;
import com.kaede.hayate.modules.sys.mapper.UserMapper;
import com.kaede.hayate.modules.sys.mapper.UserRoleMapper;
import com.kaede.hayate.modules.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Kaede
 * @since 2018-06-06
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /*@Autowired
    private IUserRoleService userRoleService;*/

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Long createUser(User user, Long[] roleIds) {
        baseMapper.insert(user);
        Long userId = user.getId();
        for(int i = 0; i < roleIds.length; i++){
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleIds[i]);
            userRoleMapper.insert(userRole);
        }
        return userId;
    }

    @Override
    public void deleteUserById(Long id) {
        baseMapper.deleteById(id);
        userRoleMapper.deleteByUserId(id);
    }

    @Override
    public void updateUserById(User user, Long[] roleIds) {
        updateById(user);
        userRoleMapper.deleteByUserId(user.getId());
        for(int i = 0; i < roleIds.length; i++){
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleIds[i]);
            userRoleMapper.insert(userRole);
        }
    }
}
